package com.jly.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jly.common.Constants;
import com.jly.common.Result;
import com.jly.controller.dto.UserDTO;
import com.jly.controller.dto.UserPasswordDTO;
import com.jly.entity.User;
import com.jly.mapper.userMapper;
import com.jly.service.IUserService;
import com.mysql.cj.result.Row;
import org.apache.ibatis.annotations.Delete;
import org.apache.poi.sl.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private userMapper userMapper;
    @Autowired
    private IUserService userService;

    /**
     * 登录
     */
    @PostMapping("/login")
    public Result login(@RequestBody UserDTO userDTO,HttpServletResponse response) {
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            return Result.error(Constants.CODE_400,"参数错误");
        }else{
            UserDTO dto = userService.login(userDTO, response);
            return Result.success(dto);
        }

    }
    /**
     * 注册
     */
    @PostMapping("/register")
    public Result register(@RequestBody UserDTO userDTO) {
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            return Result.error(Constants.CODE_400,"参数错误");
        }else{
            User register = userService.register(userDTO);
            return  Result.success(register);
        }

    }

    /*      @GetMapping("/")
            public Map<String, Object> selectPage(@RequestParam Integer pageNum, @RequestParam Integer pageSize) {
              Map<String, Object> res = new HashMap<>();
              Page<User> userPage = userMapper.selectPage(Page.of(pageNum, pageSize), new QueryWrapper<>());
              res.put("data", userPage.getRecords());
              res.put("total", userPage.getTotal());
              return res;

            }*/
    /*
       // 分页查询 - mybatis-plus的方式
    @GetMapping("/page")
    public IPage<User> findPage(@RequestParam Integer pageNum,
                                @RequestParam Integer pageSize,
                                @RequestParam(defaultValue = "") String username,
                                @RequestParam(defaultValue = "") String email,
                                @RequestParam(defaultValue = "") String address) {
        IPage<User> page = new Page<>(pageNum, pageSize);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (!"".equals(username)) {
            queryWrapper.like("username", username);
        }
        if (!"".equals(email)) {
            queryWrapper.like("email", email);
        }
        if (!"".equals(address)) {
            queryWrapper.like("address", address);
        }
        queryWrapper.orderByDesc("id");
        return userService.page(page, queryWrapper);
    }

}
     */

    /**
     * 分页查询模糊查询 - mybatis-plus的方式
     * @param pageNum
     * @param pageSize
     * @param username
     * @param email
     * @param address
     * @return
     */
    @GetMapping("/page") // 分页模糊查询
    public Result selectPage(@RequestParam Integer pageNum,
                                          @RequestParam Integer pageSize,
                                          @RequestParam(required = false, defaultValue = "") String username,
                                          @RequestParam(required = false, defaultValue = "") String email,
                                          @RequestParam(required = false, defaultValue = "") String address
    ) {
//        Map<String, Object> res = new HashMap<>();
//        Page<User> search = userService.search("%" + username + "%", "%" + email + "%", "%" + address + "%", pageNum, pageSize);
//        System.out.println(search.getTotal());
//        res.put("Records", search.getRecords());
//        res.put("total", search.getTotal());
//      //  return res;
//        return Result.success(res);
        Page<User> userPage = userService.findPage(new Page<>(pageNum, pageSize), username, email, address);
        return Result.success(userPage);
    }

    /**
     * 新增或修改用户
     * @param user
     * @return
     */
    @PostMapping("/updateOrSave")
    public Result saveOrUpdate(@RequestBody User user) {
//       // return userService.saveUser(user);
//        boolean saveUser = userService.saveUser(user);
//        return Result.success(saveUser);
        if (user.getId() == null && user.getPassword() == null) {
            user.setPassword(SecureUtil.md5("123"));
        }
        return Result.success(userService.saveOrUpdate(user));

    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        boolean removeById = userService.removeById(id);
        return  Result.success(removeById);

    }

    /**
     * 批量删除用户
     * @param ids
     * @return
     */
    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        boolean removeBatchByIds = userService.removeBatchByIds(ids);
        return Result.success(removeBatchByIds);
    }

    @PostMapping("/password")
    public Result  password(@RequestBody UserPasswordDTO userPasswordDTO){
        userPasswordDTO.setPassword(SecureUtil.md5(userPasswordDTO.getPassword()));
        userPasswordDTO.setNewPassword(SecureUtil.md5(userPasswordDTO.getNewPassword()));
        userService.UpdatePassword(userPasswordDTO);
        return Result.success();
    }

    @GetMapping("username/{username}")
    public Result findUserByUsername(@PathVariable String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
       return Result.success(userService.getOne(queryWrapper));
    }
    @GetMapping("/role/{role}")
    public Result findUsersByRole(@PathVariable String role) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role", role);
        List<User> list = userService.list(queryWrapper);
        return Result.success(list);
    }

    /**
     * 导出excle
     * @param response
     * @throws UnsupportedEncodingException
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws UnsupportedEncodingException {
        // 数据库查询数据
        List<User> list = userService.list();
        // 通过工具类创建writer 写出到磁盘路径
        //ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath+"用户信息.xlsx");
        // 基于内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        // 自定义标签列名
//        writer.addHeaderAlias("username", "用户名");
//        writer.addHeaderAlias("password", "密码");
//        writer.addHeaderAlias("nickname", "昵称");
//        writer.addHeaderAlias("email", "邮箱");
//        writer.addHeaderAlias("phone", "电话");
//        writer.addHeaderAlias("address", "地址");
//        writer.addHeaderAlias("createTime", "创建时间");
//        writer.addHeaderAlias("avatarUrl", "头像");
        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);
        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            writer.flush(outputStream, true);
            outputStream.close();
            writer.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 导入excle
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/import")
    public boolean imp(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        // 方式1：(推荐) 通过 javabean的方式读取Excel内的对象，但是要求表头必须是英文，跟javabean的属性要对应起来
        try {
            List<User> list = reader.readAll(User.class);
            System.out.println("list" + list);
            userService.saveBatch(list);
            return true;

        } catch (Exception e) {
            System.out.println("异常" + e.getMessage());
            return false;
        }
    }

}